#include "GBFont.h"
#include <stdio.h>
#include <vector>
#include <io.h>

using std::string;
using std::vector;

// Static Variables:
///////////////
GBFontFactory GBFontFactory::m_factory;
GBFreeType GBFont::m_fonter;
//////////////

GBFont::GBFont() : m_nID(-1), m_pt(0)
{

}

GBFont::~GBFont()
{

}

bool GBFont::BuildFont(const char* szFileName, long pt)
{
	if(szFileName == NULL) return false;

	m_pt = pt;

	m_fontFace = string(szFileName);
	std::string fileName(szFileName);

 	// Search in own directory for fonts
	if(_access(fileName.c_str(), 0) != -1)
		m_nID = m_fonter.CreateFace(fileName.c_str(), pt);
	else	// Search in main directory in windows
	{
		fileName = "C:/Windows/Fonts/";
		fileName += m_fontFace;

		if(_access(fileName.c_str(), 0) != -1)
			m_nID = m_fonter.CreateFace(fileName.c_str(), pt);
		else return false;
	}

	// Check if there was still an error with the font being loaded
	return (m_nID >= 0);
}

void GBFont::KillFont()
{
	m_fonter.DestroyFace(m_nID);
}

void GBFont::Print(const char* szFmt, ...) const
{
	if(m_nID == -1) return;
	if(szFmt == NULL) return;
                           
	char szText[512];	// Holds Our String

	va_list	ap;	// Pointer To List Of Arguments

	va_start(ap, szFmt); // Parses The String For Variables
		vsprintf_s(szText, 256, szFmt, ap); // And Converts Symbols To Actual Numbers
	va_end(ap);// Results Are Stored In Text

	// Draw all the lines (offsetted to the ALIGN_CENTER of the drawn text)
	m_fonter.Render(szText, m_nID);
}

GBFont* GBFontFactory::GetFont(const char* szFontFace, const long pt)
{
	std::deque<GBFont>::iterator pIter;
	for(pIter = m_fonts.begin(); pIter != m_fonts.end(); pIter++)
	{
		if((strcmp((*pIter).GetFace(), szFontFace) == 0))
			if((*pIter).GetPtSize() == pt)
				return &(*pIter);
	}

	// Add the new font then
	GBFont pFont;
	if(pFont.BuildFont(szFontFace, pt))
	{
		m_fonts.push_back(pFont);
		return &m_fonts[m_fonts.size() - 1];
	}

	return NULL;
}

void GBFontFactory::ClearFonts()
{
	std::deque<GBFont>::iterator pIter;
	for(pIter = m_fonts.begin(); pIter != m_fonts.end(); pIter++)
		(*pIter).KillFont();

	m_fonts.clear();
}

GBFontFactory::GBFontFactory() 
{

}